package transport

import (
	"context"
	"encoding/json"
	"io"
	"net/http"

	"goKit/global"
	"goKit/params/req"
)

func DecodeVcRequest(_ context.Context, r *http.Request) (interface{}, error) {
	return r, nil
}

func DecodeInputUserRequest(_ context.Context, r *http.Request) (interface{}, error) {
	// token 解析 - 待加时间的限制以及续费机制
	cla, ok := global.GetParam2(r.Header.Get("token"))
	if !ok {
		return nil, nil
	}
	// 参数校验
	all, _ := io.ReadAll(r.Body)
	defer r.Body.Close()
	in := req.InputUser{}
	_ = json.Unmarshal(all, &in)
	in.UID = cla.UID
	in.UserName = cla.UserName
	if in.Age < 20 {
		return nil, nil
	}
	return &in, nil
}

func EncodeVcResponse(_ context.Context, w http.ResponseWriter, response interface{}) error {
	SetResponseWrite(&w)
	return json.NewEncoder(w).Encode(response)
}

// 设置跨域以及返回值格式
func SetResponseWrite(w *http.ResponseWriter) {
	(*w).Header().Set("Access-Control-Allow-Origin", "*")
	(*w).Header().Set("Access-Control-Allow-Credentials", "true")
	(*w).Header().Set("Access-Control-Methods", "POST, PUT, PATCH, DELETE")
	(*w).Header().Set("Access-Control-Allow-Headers", "Access-Control-Allow-Origin,Content-Type,X-API-CHANNEL,Token")
	(*w).Header().Set("Access-Control-Max-Age", "86400")
	(*w).Header().Set("Content-type", "application/json")
}
